package com.bjpowernode.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjpowernode.shop.base.BaseManagerService;
import com.bjpowernode.shop.domain.SysRole;
import com.bjpowernode.shop.domain.SysRoleMenu;
import com.bjpowernode.shop.domain.SysUser;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseManagerService {

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public ResponseEntity<List<SysRole>> getAllRoleList() {
        return ResponseEntity.ok(sysRoleService.list());
    }

    @GetMapping("/page")
    public ResponseEntity<Page<SysRole>> getRolePage(Page<SysRole> page, @RequestParam(value = "roleName", required = false) String roleName) {
        return ResponseEntity.ok(
                sysRoleService.page(page,
                        new LambdaQueryWrapper<SysRole>()
                                .like(StringUtils.hasText(roleName), SysRole::getRoleName, roleName)));
    }

    @PostMapping
    @Transactional
    public ResponseEntity<Boolean> saveRole(@RequestBody SysRole sysRole) {
        boolean flag = sysRoleService.save(
                sysRole.setCreateUserId(getLongUserId())
                        .setCreateTime(new Date()));

        if (!flag) {
            throw new RuntimeException("新增角色失败");
        }

        // 根据角色对象中的菜单id列表MenuIdList，构建出角色和菜单的关联关系表roleMenuList
        List<SysRoleMenu> roleMenuList = sysRole.getMenuIdList().stream().map(menuId -> {
            return SysRoleMenu.builder().roleId(sysRole.getRoleId()).menuId(menuId).build();
        }).collect(Collectors.toList());

        // 批量新增关联关系表
        sysRoleMenuService.saveBatch(roleMenuList);

        return ResponseEntity.ok(flag);
    }

    // ==修改角色 角色列表信息==
    // 查询指定角色的角色信息
    @GetMapping("/info/{id}")
    @Transactional
    public ResponseEntity<SysRole> getInfo(@PathVariable Long id) {
        System.out.println("====id = " + id);
        // 查角色信息
        SysRole sysRole = sysRoleService.getById(id);

        // 查关联列表
        List<SysRoleMenu> list = sysRoleMenuService.list(
                new LambdaQueryWrapper<SysRoleMenu>().eq(
                        SysRoleMenu::getRoleId, id
                )
        );

        // 设置关联列表
        List<Long> menuIdList = new ArrayList<>();
        for (SysRoleMenu sysRoleMenu : list) {
            menuIdList.add(sysRoleMenu.getMenuId());
        }
        sysRole.setMenuIdList(menuIdList);

        System.out.println("====sysRole = " + sysRole);
        return ResponseEntity.ok(sysRole);
    }

    // 提交修改角色信息表单
    @PutMapping
    @Transactional
    public ResponseEntity<Boolean> updateSysRole(@RequestBody SysRole sysRole) {
        // sysRole.setCreateUserId(1L);
        // sysRole.setCreateTime(new Date());
        System.out.println("===sysRole = " + sysRole);

        // 修改角色信息
        boolean flag1 = sysRoleService.updateById(sysRole);

        // boolean flag11 = sysRoleService.saveOrUpdate(sysRole);
        // boolean flag111 = sysRoleService.update(
        //         sysRole,
        //         new LambdaQueryWrapper<SysRole>().eq(
        //                 SysRole::getRoleId, sysRole.getRoleId()
        //         )
        // );

        if (!flag1)
            throw new RuntimeException("修改角色信息失败");

        // 构造修改后的关联
        List<SysRoleMenu> roleMenuList = sysRole.getMenuIdList().stream().map(
                menuId -> {
                    return SysRoleMenu.builder()
                            .menuId(menuId)
                            .roleId(sysRole.getRoleId())
                            .build();
                }
        ).collect(Collectors.toList());

        // 批量删除原关联
        boolean flag2 = sysRoleMenuService.remove(
                new LambdaQueryWrapper<SysRoleMenu>().eq(
                        SysRoleMenu::getRoleId, sysRole.getRoleId()
                )
        );
        if (!flag2)
            throw new RuntimeException("批量删除原关联失败");

        // 批量新增修改后关联
        boolean flag3 = sysRoleMenuService.saveBatch(roleMenuList);
        if (!flag3)
            throw new RuntimeException("批量新增修改后关联失败");


        boolean flag = flag1 && flag2 && flag3;
        return ResponseEntity.ok(flag);
    }

    // 删除角色信息
    @DeleteMapping
    @Transactional
    public ResponseEntity<Boolean> delSysRole(@RequestBody List<Long> ids) {
        System.out.println("===ids = " + ids);

        // 删除角色信息
        boolean flag1 = sysRoleService.removeByIds(ids);
        if (!flag1)
            throw new RuntimeException("删除角色信息失败");

        // 删除关联信息
        for (Long id : ids) {
            boolean flag2 = sysRoleMenuService.remove(new LambdaQueryWrapper<SysRoleMenu>().eq(
                    SysRoleMenu::getRoleId, id
            ));
            if (!flag2)
                throw new RuntimeException("删除角色菜单关联失败");
        }
        
        return ResponseEntity.ok(flag1);
    }
}
